package cn.ztydata.teachingsystem.heaven.web.controller;

import cn.ztydata.teachingsystem.common.Page;
import cn.ztydata.teachingsystem.exception.ServiceException;
import cn.ztydata.teachingsystem.heaven.cons.MsgTemplate;
import cn.ztydata.teachingsystem.heaven.cons.Roles;
import cn.ztydata.teachingsystem.heaven.entity.Specialty;
import cn.ztydata.teachingsystem.heaven.entity.User;
import cn.ztydata.teachingsystem.heaven.service.CourseService;
import cn.ztydata.teachingsystem.heaven.service.ResourceService;
import cn.ztydata.teachingsystem.heaven.service.SpecialtyService;
import cn.ztydata.teachingsystem.heaven.web.dto.SpecialtyDto;
import cn.ztydata.teachingsystem.heaven.web.wrapper.HttpSessionProxy;
import cn.ztydata.teachingsystem.util.StringCodeUtil;
import cn.ztydata.teachingsystem.webservice.result.json.JsonResult;
import cn.ztydata.teachingsystem.webservice.result.json.JsonResultData;
import cn.ztydata.teachingsystem.webservice.result.json.JsonResultList;
import cn.ztydata.teachingsystem.webservice.result.json.JsonResultPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 专业控制器类
 *
 * @author fanruiping
 * @since 2014-12-01
 */
@RequestMapping("/major")
@Controller
public class SpecialtyController extends BaseController {
    @Autowired
    private SpecialtyService specialtyService;
    @Autowired
    private ResourceService resourceService;
    @Autowired
    private CourseService courseService;
    @Value("${session.key}")
    private String sessionKey;

    /**
     * 获取专业数据列表
      * @param pageNum 页码
     * @param deptNum 系部编码
     * @return JsonResult
     *
     * @author fanruiping
     * @since 2014-12-01
     */
    @RequestMapping(value = "/list/{pageNum}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult list(@PathVariable int pageNum,
                           @RequestParam(value = "pageSize",required = false, defaultValue = "1") int pageSize,
                           @RequestParam(value = "departCode",required = false, defaultValue = "") String deptNum,
                           HttpServletRequest request){
        pageSize = pageSize < 1 ? 1 : pageSize;

        pageNum = pageNum < 1 ? 1 : pageNum;

        User userInfo = (User)((HttpSessionProxy)request.getSession()).getAttribute(sessionKey);

        Page<Specialty> page = specialtyService.getList(userInfo,deptNum, pageNum, pageSize);

        Page<SpecialtyDto> dtoPage = new Page<>(page.getTotal(), page.getSize(), page.getNum(),mapper.mapList(page.getItems(), SpecialtyDto.class));

        log.debug("return specialty list");

        return new JsonResultPage<>(dtoPage);
    }

    /**
     * 专业下拉数据
     * @param deptNum 系部编码
     * @param tag 标记（0：全部，1：根据角色获取）
     * @return JsonResult
     *
     * @author fanruiping
     * @since 2014-12-01
     */
    @RequestMapping(value = "/dropdownList/{deptNum}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult dropdownList(@PathVariable String deptNum,@RequestParam(value = "tag", defaultValue = "0", required = false) int tag){
        List<Specialty> entities = new ArrayList<>();

        if("all".equals(deptNum)){
            log.debug("系部编码为All:\"all\".equals(deptNum)");

            entities = specialtyService.getAll();
        }else{
            log.debug("系部编码不为all:!\"all\".equals(deptNum)");

            entities = specialtyService.getByDeptNum(deptNum,tag);
        }

        log.debug("return specialty list");

        return new JsonResultList<>(mapper.mapList(entities, SpecialtyDto.class));
    }

    /**
     * 新增专业
     * @param dto
     * @return JsonResult
     *
     * @author fanruiping
     * @since 2014-12-01
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult add(@Valid @RequestBody SpecialtyDto dto){
        //根据专业编码判断数据是否已存在
        if(null != specialtyService.getDetailByNumber(dto.getCode())){
            log.debug("specialty code is exist");

            return new JsonResult(false, "专业编码为"+dto.getCode()+"的数据已存在");
        }

        specialtyService.add(mapper.map(dto, Specialty.class));

        log.debug("add specialty success:return true");

        return new JsonResult(true, "专业数据添加成功");
    }

    /**
     * 编辑专业数据
     * @param dto
     * @return JsonResult
     *
     * @author fanruiping
     * @since 2014-12-01
     */
    @RequestMapping(value = "/edit", method = RequestMethod.PUT)
    @ResponseBody
    public JsonResult edit(@Valid @RequestBody SpecialtyDto dto){
        Specialty entity = specialtyService.getDetail(dto.getId());

        //判断数据是否存在
        if(null == entity){
            log.debug("specialty is not exist:null == entity");

            return new JsonResult(false, "更新的专业数据不存在");
        }

        //根据专业编码判断数据是否存在
        if(entity.getNumber() != dto.getCode() && null != specialtyService.getDetailByNumberAndId(dto.getCode(), dto.getId())){
            log.debug("new number is exist:entity.getNumber() != dto.getCode() && null != specialtyService.getDetailByNumberAndId(dto.getCode(), dto.getId())");

            return new JsonResult(false, "专业编码为"+dto.getCode()+"的数据已存在");
        }

        try {
            specialtyService.modify(mapper.map(dto, Specialty.class));

            log.debug("update specialty success:return true");

            return new JsonResult(true, "专业数据更新成功");
        }catch(ServiceException ex){
            log.debug("update specialty fail:return true");

            return new JsonResult(true, "专业数据更新失败");
        }
    }

    /**
     * 删除专业
     * @param id 编号
     * @return JsonResult
     *
     * @author fanruiping
     * @since 2014-12-01
     */
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public JsonResult delete(@PathVariable long id){
        Specialty entity = specialtyService.getDetail(id);

        //判断数据是否存在
        if(null == entity){
            log.debug("specialty is not exist:null==entity");

            return new JsonResult(false, "专业数据不存在");
        }

        //判断该专业下是否有资源和课程
        if(resourceService.checkHasResourceBySpecId(id) || courseService.checkHasCourseBySpecId(id)){
            log.debug("专业下有资源或课程:resourceService.checkHasResourceBySpecId(id) || courseService.checkHasCourseBySpecId(id)");

            return new JsonResult(false, "请先删除该专业下的资源或课程，再执行删除");
        }

        //判断数据是否删除成功
        if(1 > specialtyService.delete(id)){
            log.debug("delete specialty fail:return false");

            return new JsonResult(false, "专业数据删除失败");
        }

        log.debug("delete specialty success:return true");

        return new JsonResult(true, "专业数据删除成功");
    }

    /**
     * 专业明细数据
     * @param id 编号
     * @return JsonResult
     *
     * @author fanruiping
     * @since 2014-12-01
     */
    @RequestMapping(value = "/detail/{id}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult detail(@PathVariable long id){
        Specialty entity = specialtyService.getDetail(id);

        if(null == entity){
            log.debug("specialty is not exist:null==entity");

            return new JsonResultData<>(false, "查看的专业数据不存在");
        }

        log.debug("specialty is exist:return specialty detail");

        return new JsonResultData<>(mapper.map(entity, SpecialtyDto.class));
    }

    /**
     * 专业列表（包括专业下资源数量）
     * @param type 类型 (ALL:所有专业，MANAGER:专业负责人负责的)
     * @return JsonResult
     *
     * @author fanruiping
     * @since 2014-12-16
     */
    @RequestMapping(value = "/resList/{type}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult resList(@PathVariable String type,
                              @RequestParam(value = "search",required = false, defaultValue = "") String keyword,
                              HttpServletRequest request){
        HttpSessionProxy httpSessionProxy = (HttpSessionProxy)request.getSession();

        //搜索关键字转码
        keyword = StringCodeUtil.urlParamTransCode(keyword, "utf-8");

        //获取当前用户信息
        User user = (User)httpSessionProxy.getAttribute(sessionKey);

        List<Specialty> entities = resourceService.countForSpec(keyword,type, user.getUserId(), user.getRole());

        log.debug("return specialty list");

        return new JsonResultList<>(mapper.mapList(entities, SpecialtyDto.class));
    }

    /**
     * 获取专业负责人负责的专业列表
     * @param request
     * @return JsonResult
     *
     * @author fanruiping
     * @since 2014-12-23
     */
    @RequestMapping(value = "/leadingDropdownList", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult leadingDropdownList(HttpServletRequest request){
        //获取当前登录用户信息
        User user = (User)((HttpSessionProxy)request.getSession()).getAttribute(sessionKey);

        List<Specialty> entities;

        if(user.getRole() == Roles.SUPER_ADMIN || user.getRole() == Roles.COLLEGE_USER){
            log.debug("用户角色是超级管理员或院级用户:user.getRole() == Roles.SUPER_ADMIN || user.getRole() == Roles.COLLEGE_USER");

            entities = specialtyService.getAll();
        }
        else if (Roles.DEPT_ADMIN == user.getRole()) {
            log.debug("用户角色是系部管理员:Roles.DEPT_ADMIN == user.getRole()");

            entities = specialtyService.getForDeptLeader(user.getUserId());
        }
        else{
            log.debug("用户角色不是超级管理员也不是院级用户");

            entities = specialtyService.getByLeaderId(user.getUserId());
        }

        log.debug("return specialty list");

        return new JsonResultList<>(mapper.mapList(entities, SpecialtyDto.class));
    }

    /**
     * 获取首页专业列表信息
     *
     * @author chenxin
     * @since 2015/1/10
     */
    @RequestMapping(value = "/indexList/{deptNum}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResultList<SpecialtyDto> getIndexList(@PathVariable String deptNum) {
        //校验参数
        Assert.hasText(deptNum, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "系部编码"));

        //获取指定系部的前5个专业信息
        List<Specialty> specList = specialtyService.getIndexList(deptNum, 5);

        log.debug("获取首页专业列表信息");
        return new JsonResultList<>(mapper.mapList(specList, SpecialtyDto.class));
    }

    /**
     * 专业资源统计
     * @param search 搜索关键字
     * @return JsonResult
     *
     * @author fanruiping
     * @since 2015-05-06
     */
    @RequestMapping(value = "/myResourceStatistics", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult majorResourceStatistics(@RequestParam String search,@RequestParam int tag){
        Assert.isTrue(tag == 0 || tag == 1,MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "标记"));

        //搜索关键字转码
        search = StringCodeUtil.urlParamTransCode(search, "utf-8");

        List<Map<String,Object>> groupResource = resourceService.getGroupResourceStatistics(tag,0,search);

        return new JsonResultList<>(groupResource);
    }
}
